package com.liang.config;

import org.springframework.context.annotation.Bean;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.crypto.password.NoOpPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.security.provisioning.InMemoryUserDetailsManager;

/**
 * 安全配置：用户信息、密码编码器、安全拦截机制
 * @author Liangxp
 * @date 2021/5/13 21:29
 */
@EnableWebSecurity
public class WebSecurityConfig extends WebSecurityConfigurerAdapter {

    /**
     * 配置用户信息
     * @return
     */
    @Override
    @Bean
    public UserDetailsService userDetailsService() {
        InMemoryUserDetailsManager userManager = new InMemoryUserDetailsManager();
        userManager.createUser(User.withUsername("jack").password("jack123").authorities("p1").build());
        userManager.createUser(User.withUsername("tom").password("tom123").authorities("p2").build());
        return userManager;
    }

    /**
     * 配置密码编码器
     * @return
     */
    @Bean
    public PasswordEncoder passwordEncoder() {
        return NoOpPasswordEncoder.getInstance();
    }

    /**
     * 配置安全拦截机制
     * @param http
     * @throws Exception
     */
    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http.authorizeRequests()
                // 下面两路径，分别得有对应的权限才能访问
                .antMatchers("/r/r1").hasAuthority("p1")
                .antMatchers("/r/r2").hasAuthority("p2")
                // url匹配/r/**的资源，经过认证后才能访问。
                .antMatchers("/r/**").authenticated()
                // 其他url完全开放。
                .anyRequest().permitAll()
                .and()
                // 支持form表单认证，认证成功后转向/login-success。
                .formLogin().successForwardUrl("/loginSuccess");
    }
}
